import { useState, useEffect } from 'react'
import { Table, Tag, Button, Alert } from 'antd'
import axios from 'axios'
import { getAuthToken } from '@/router'

// 虚拟数据配置
const mockData = Array.from({ length: 25 }, (_, i) => ({
  id: i + 1,
  name: `种子项目 ${i + 1}`,
  status: i % 3 === 0 ? 'seeding' : 'completed',
  uploaded: Math.floor(Math.random() * 10000000),
  downloaded: Math.floor(Math.random() * 5000000),
  ratio: (Math.random() * 5).toFixed(2)
}))

const columns = [
  { 
    title: '种子名称', 
    dataIndex: 'name', 
    render: (text, record) => (
      <Button 
        type="link" 
        onClick={() => window.open(`/torrent/${record.id}`)}
        style={{ paddingLeft: 0 }}
      >
        {text}
      </Button>
    )
  },
  { 
    title: '状态', 
    dataIndex: 'status',
    render: status => (
      <Tag color={status === 'seeding' ? 'green' : 'gray'}>
        {status === 'seeding' ? '做种中' : '已完成'}
      </Tag>
    )
  },
  { 
    title: '上传量', 
    dataIndex: 'uploaded', 
    render: t => `${(t / 1024 / 1024).toFixed(2)} MB` 
  },
  { 
    title: '下载量', 
    dataIndex: 'downloaded', 
    render: t => `${(t / 1024 / 1024).toFixed(2)} MB` 
  },
  { 
    title: '分享率', 
    dataIndex: 'ratio', 
    render: r => (
      <Tag color={r >= 1 ? 'green' : 'red'}>
        {Number(r).toFixed(2)}
      </Tag>
    )
  }
]

export default function TorrentHistory() {
  const [data, setData] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)
  const [pagination, setPagination] = useState({ 
    current: 1, 
    pageSize: 10,
    showTotal: total => `共 ${total} 条记录`,
    showQuickJumper: true,
    total: 0
  })

  useEffect(() => {
    fetchData()
  }, [pagination.current])

  const fetchData = async () => {
    try {
      setLoading(true)
      setError(null)
      
      // 真实API请求
      const res = await axios.get('/api/v1/user/torrent-history', {
        headers: { Authorization: `Bearer ${getAuthToken()}` },
        params: {
          page: pagination.current,
          size: pagination.pageSize
        }
      })
      
      // 开发环境使用虚拟数据
      const isDev = process.env.NODE_ENV === 'development'
      const responseData = isDev ? {
        list: mockData.slice(
          (pagination.current - 1) * pagination.pageSize,
          pagination.current * pagination.pageSize
        ),
        total: mockData.length
      } : res.data.data

      setData(responseData.list || [])
      setPagination(prev => ({
        ...prev,
        total: responseData.total || 0,
        current: isDev ? pagination.current : responseData.page || 1
      }))

    } catch (error) {
      console.error('获取数据失败:', error)
      setError('无法获取数据，已显示演示数据')
      // 降级显示虚拟数据
      setData(mockData.slice(0, 10))
      setPagination(prev => ({
        ...prev,
        total: mockData.length
      }))
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="torrent-history">
      {error && (
        <Alert
          message="演示数据提示"
          description="当前显示的是模拟数据，实际数据需要连接服务器获取"
          type="info"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />
      )}
      
      <Table
        columns={columns}
        rowKey="id"
        dataSource={data}
        pagination={pagination}
        loading={loading}
        onChange={newPagination => {
          setPagination(prev => ({
            ...prev,
            current: newPagination.current
          }))
        }}
        bordered
        scroll={{ x: 800 }}
        locale={{
          emptyText: error ? '无法加载数据' : '暂无种子记录'
        }}
      />
    </div>
  )
}